import nano from './nano'

import { _decorator } from 'cc';
import {DEBUG} from "cc/env";
const { ccclass } = _decorator;

@ccclass('Server')
export class Server {
    static s:nano;
    public static init(host:string, port:number, path: string, maxReconnectAttempts: number, cb?: Function){
        if (!cb) {
            cb = () => {
                console.log("server connected...");
            }
        }
        Server.s = new nano();
        Server.s.init({
            host:host,
            port:port,
            path: path,
            reconnect:true,
            // 重连次数
            maxReconnectAttempts: maxReconnectAttempts,
        },cb)
    }

    public static listen(route: string, callback: Function){
        Server.s.on(route, async (resp: any) =>{
            if (DEBUG) {
                console.log(`receive push message ${route}`, resp)
            }
            await callback(resp);
        })
    }

    // 取消监听
    public static listenOff(route: string){
        Server.s.off(route)
    }

    // 只监听一次
    public static listenOnce(route: string, callback: Function) {
        Server.s.on(route, async (resp: any) =>{
            Server.s.off(route)
            await callback(resp);
        })
    }

    public static request(route: string, msg: any, callback?:Function){
        if (DEBUG) {
            // debug模式
            console.log(`request ${route} with`, msg)
        }
        Server.s.request(route,msg,async (response: any)=>{
            if (callback) {
                if (DEBUG) {
                    // debug模式
                    console.log(`receive ${route} with`, response)
                }
                await callback(response)
            }
        })
    }
    public static nofity(route: string, msg: any){
        Server.s.notify(route,msg)
    }
    public static disconnect(){
        Server.s.disconnect();
    }
}
